package nl.fotoniq.android.lockpicker.shared;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.provider.Settings;

/**
 * The Class LockPickerService.
 * <p>
 * This service registers a {@link LockPickerObserver} which notifies the service when the lock setting should be
 * changed.
 * </p>
 * 
 * @author jeroen.brosens
 */
public class LockPickerService extends Service {

	private static final int VALUE_LOCK_ENABLED = 1;
	private static final int VALUE_LOCK_DISABLED = 0;

	private LockPickerObserver lockSettingObserver = null;

	private Handler lockSettingChangedHandler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == LockPickerObserver.LOCK_SETTING_CHANGED_MESSAGE) {
				toggleLock(LockPickerConstants.DEFAULT_LOCK_SETTING_ON_START);
			}
		}
	};

	/**
	 * {@inheritDoc}
	 * 
	 * @see android.app.Service#onBind(android.content.Intent)
	 */
	@Override
	public IBinder onBind(Intent intent) {
		LockPickerUtil.log_d("Bound LockPicker service");

		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		LockPickerUtil.log_d("LockPicker service started");

		toggleLock(LockPickerConstants.DEFAULT_LOCK_SETTING_ON_START);
		registerObserver();

		return START_STICKY;
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @see android.app.Service#onDestroy()
	 */
	@Override
	public void onDestroy() {
		super.onDestroy();

		unregisterObserver();
		toggleLock(LockPickerConstants.DEFAULT_LOCK_SETTING_ON_STOP);

		LockPickerUtil.log_d("LockPicker service destroyed");
	}

	private void registerObserver() {
		lockSettingObserver = new LockPickerObserver(lockSettingChangedHandler);
		getContentResolver().registerContentObserver(LockPickerConstants.LOCK_SETTING_URI, false, lockSettingObserver);

		LockPickerUtil.log_d("Registered observer");
	}

	private void unregisterObserver() {
		if (lockSettingObserver == null) {
			return;
		}

		getContentResolver().unregisterContentObserver(lockSettingObserver);
		lockSettingObserver = null;

		LockPickerUtil.log_d("Unregistered observer");
	}

	private void toggleLock(final boolean isLockEnabled) {
		LockPickerUtil.log_d("Toggling lock");

		Settings.System.putInt(getContentResolver(), LockPickerConstants.LOCK_SETTING_NAME,
				isLockEnabled ? VALUE_LOCK_ENABLED : VALUE_LOCK_DISABLED);

		final String notification = isLockEnabled ? getString(R.string.exchange_lockscreen_enabled)
				: getString(R.string.exchange_lockscreen_disabled);

		LockPickerUtil.log_d(notification);

		LockPickerNotifier.showNotification(this, R.drawable.ic_stat_notify_lock, getString(R.string.app_name),
				notification, notification);
	}
}
